package com.lottery.game.controller.v2.notice;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lottery.game.annotation.Current;
import com.lottery.game.common.BaseQuery;
import com.lottery.game.common.Response;
import com.lottery.game.constants.RespErrorCodes;
import com.lottery.game.core.model.dto.UserToken;
import com.lottery.game.core.model.dto.game.GameAnnouncementTO;
import com.lottery.game.core.modules.entity.game.GameAnnouncement;
import com.lottery.game.core.modules.entity.game.GameAnnouncementUser;
import com.lottery.game.core.modules.service.game.GameAnnouncementService;

import com.lottery.game.core.modules.service.game.GameAnnouncementUserService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import springfox.documentation.annotations.ApiIgnore;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletResponse;

/**
 * @author : yinlin
 * @version : 1.0
 * @date : 2019-02-04 09:48
 * @Description :
 * @Copyright : Copyright (c) 2018
 * @Company : KeRuYun Technology(Beijing) Chengdu Co. Ltd.
 * @link : com.runshang.apps.cloudgame.controller.v2.advert.NoticeController
 */
@RestController
@RequestMapping("/api/v2/system/notice")
@Api(tags = "APP-系统公告接口")
@Slf4j
public class NoticeController {

    @Autowired
    private GameAnnouncementService gameAnnouncementService;

    @Autowired
    private GameAnnouncementUserService gameAnnouncementUserService;

    @PostMapping(value = "findUserlist",produces = {org.springframework.http.MediaType.APPLICATION_JSON_UTF8_VALUE})
    @ApiImplicitParam(name = "ticket", value = "ticket", dataType = "String", paramType = "header",required = true)
    @ApiOperation(value = "获取用户是否已读系统公告列表" ,notes = "获取用户是否已读系统公告列表 ")
    public Response<NoticeResponse> findUserlist(@ApiIgnore @Current UserToken ticket,@RequestBody BaseQuery query) {

        try {
        	Map<String,Object> resultMap = new HashMap<>();
        	//未读数量
        	int notReadNum = 0;
            //构造条件查询
            Example example = new Example(GameAnnouncement.class);
            example.setOrderByClause("sort ASC");
            Example.Criteria criteria = example.createCriteria();
            //未读状态
            criteria.andEqualTo("status", 0);
            //分页
            PageInfo<GameAnnouncement> pageInfo = gameAnnouncementService.selectPageByExample(example, query.getPage(), query.getRows());
            //查询用户的已读未读信息
            Example userExample = new Example(GameAnnouncementUser.class);
            Example.Criteria userExampleCriteria = userExample.createCriteria();
            userExampleCriteria.andEqualTo("userId", ticket.getId());
            List<GameAnnouncementUser> announcementUserList = gameAnnouncementUserService.selectByExample(userExample);
            List<GameAnnouncement> list = pageInfo.getList();
            //如果user没有数据,那么代表未读过一条信息,即所有公告未读
            if (CollectionUtils.isEmpty(announcementUserList)){
                for (GameAnnouncement announcement : list) {
                    announcement.setStatus(0);
                    notReadNum++;
                }
            }else {
                //判断是否不为空
                if (!CollectionUtils.isEmpty(list)){
                    //所有公告
                    for (GameAnnouncement gameAnnouncement: list){
                        //用户关联
                        for (GameAnnouncementUser user : announcementUserList) {
                            if (user.getNoticeId().equals(gameAnnouncement.getId())){
                                gameAnnouncement.setStatus(user.getNoticeStatus());
                            }
                        }
                    }
                    notReadNum = list.size()-announcementUserList.size();
                }
            }
            resultMap.put("pageList", pageInfo);
            resultMap.put("notReadNum", notReadNum);
            NoticeResponse noticeResponse = new NoticeResponse();
            noticeResponse.setNotReadNum(notReadNum);
            noticeResponse.setPageList(pageInfo);
            return Response.build(noticeResponse);
        }catch (Exception e){
            log.error(RespErrorCodes.UNKNOWN_ERROR.errorCode(), e);
            return Response.buildError(RespErrorCodes.UNKNOWN_ERROR.getErrorMsg());
        }

    }

    /*@PostMapping(value = "findUserlistCount",produces = {org.springframework.http.MediaType.APPLICATION_JSON_UTF8_VALUE})
    @ApiImplicitParam(name = "ticket", value = "ticket", dataType = "String", paramType = "header",required = true)
    @ApiOperation(value = "获取用户未读系统公告条数" ,notes = "获取用户未读系统公告条数 ")
    public Integer findUserlistCount(@ApiIgnore @Current UserToken ticket) {
        Integer integers = 0;
        try {
            //构造条件查询
            Example example = new Example(GameAnnouncement.class);
            example.setOrderByClause("sort DESC");
            //Example.Criteria criteria = example.createCriteria();
            //未读状态
            //criteria.andEqualTo("status", 0);
            //查询用户的已读未读信息
            Example userExample = new Example(GameAnnouncementUser.class);
            Example.Criteria userExampleCriteria = userExample.createCriteria();
            userExampleCriteria.andEqualTo("userId", ticket.getId());
            userExampleCriteria.andEqualTo("noticeStatus",0);
            List<GameAnnouncementUser> announcementUserList = gameAnnouncementUserService.selectByExample(userExample);
            if(!CollectionUtils.isEmpty(announcementUserList)){
                integers = announcementUserList.size();
            }
        }catch (Exception e){
            log.error(RespErrorCodes.UNKNOWN_ERROR.errorCode(), e);
        }
        return integers;
    }*/


    @PostMapping(value = "findList",produces = {org.springframework.http.MediaType.APPLICATION_JSON_UTF8_VALUE})
    @ApiOperation(value = "获取系统公告列表" ,notes = "获取系统公告列表 " +
            "请求参数(要求按照文档放置参数位置):" +
            "\n{\n" + "    \"endDate\": \"2019-06-15\",\n" + "    \"page\": 1,\n" + "    \"rows\": 10,\n" + "    \"startDate\": \"2019-04-15\"\n" + "}")
    public Page<GameAnnouncement> findList(@RequestBody BaseQuery query) {
        //开启分页
        query.pageStart();
        Example example = new Example(GameAnnouncement.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andBetween("createDate", query.getStartDate(),query.getEndDate());
        //条件查询
        return (Page<GameAnnouncement>)gameAnnouncementService.selectByExample(example);
    }


    @GetMapping(value = "new/one",produces = {"application/json;charset=UTF-8"})
    @ApiOperation(value = "获取系统公告最新记录")
    public GameAnnouncementTO newOne() {
        PageHelper.startPage(0, 1);
        List<GameAnnouncement> gameAnnouncements = gameAnnouncementService.selectAll();
        if (gameAnnouncements.size() > 0) {
            return gameAnnouncements.get(0).convert(GameAnnouncementTO.class);
        }
        return null;
    }

    @PostMapping(value = "/new/getOneById",produces = {"application/json;charset=UTF-8"} )
    @ApiOperation(value = "更改某一条公告的未读状态",notes = "更改某一条公告的未读状态 " +
            "请求参数(要求按照文档放置参数位置):" +
            "\nid:789e5783722a49feb3962acea1ffcc45"+
            "\nticket:eyJpZCI6IjMxNjNjYzY3Mzg0ZDRkNWViNmFmZThlMGZlMDJiYzlhIiwibG9naW5UaW1lIjoxNTU1Mjk3MTA3ODczLCJwaG9uZSI6IjE1MzQ4OTA0MjI4Iiwic2lnbiI6ImMxMWEwOTMwMzkyNDMwMjE2YzA5NWJjZThjNjM3ODcxIiwidXNlcm5hbWUiOiIxMjMifQ==")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "id", value = "id",dataType = "String",required = true),
            @ApiImplicitParam(name = "ticket", value = "ticket", dataType = "String", paramType = "header",required = true)
    })
    public Response getOneByID(@RequestParam(name = "id") String id, @ApiIgnore @Current UserToken ticket, HttpServletResponse response) {
        try {
            //1.判断是否存在
            Example example = new Example(GameAnnouncementUser.class);
            Example.Criteria criteria = example.createCriteria();
            String userId = ticket.getId();
            criteria.andEqualTo("userId", userId);
            criteria.andEqualTo("noticeId", id);
            GameAnnouncementUser announcementUser = gameAnnouncementUserService.selectOneByExample(example);
            //2.不存在就新增
            if( null == announcementUser){
                announcementUser = new GameAnnouncementUser();
                announcementUser.setNoticeId(id);
                announcementUser.setUserId(userId);
                announcementUser.setNoticeStatus(1);
                gameAnnouncementUserService.insert(announcementUser);
            }else {
                announcementUser.setNoticeStatus(1);
                gameAnnouncementUserService.update(announcementUser);
            }
        }catch (Exception e){
            return Response.buildError("修改失败");
        }
        return Response.buildSuccess("修改成功");
    }

}